package com.kingsoft.dc.khaos.plugin.core.deploy;

import com.alibaba.fastjson.JSON;
import com.kingsoft.dc.khaos.plugin.core.KhaosConf;
import com.kingsoft.dc.khaos.plugin.core.KhaosContext;
import com.kingsoft.dc.khaos.plugin.core.utils.FileUtils;
import com.kingsoft.dc.khaos.plugin.core.utils.KhaosUtils;
import com.kingsoft.dc.khaos.plugin.core.utils.Logging;
import com.kingsoft.dc.khaos.plugin.core.utils.Utils;
import org.apache.commons.cli.*;

import java.util.Map;

/**
 * Created by jing on 19/7/24.
 */
public class AppLaunch extends Logging {
    private void exitFn(int exitCode) {
        System.exit(exitCode);
    }

    public void run(String[] args) {
        String userConfig = getUserConfig(args);
        KhaosConf khaosConf = new KhaosConf();
        khaosConf.set("khaos.app.json", userConfig);
        // 输出用户配置中的Json
//        if (true) {
//            logInfo("------------Json begin-----------");
//            for (String arg : args) {
//                logInfo(arg);
//            }
//            logInfo("------------Json end-------------");
//        }
        KhaosContext kc = new KhaosContext(khaosConf);
        kc.runApp();
        exitFn(0);
    }

    private String getUserConfig(String[] args) {
        String[] newArgs = Utils.formatMainArg(args);
        CommandLineParser parser = new DefaultParser();
        Options options = new Options();
        options.addOption("c", "userConfig", true, "Print this usage information");
        options.addOption("j", "jars", true, "");
        // Parse the program arguments
        CommandLine commandLine = null;
        String userConfig = "";

        // TODO xixi 读取本地配置文件。 闫肃，args 给出一个可用参数示例
//        if (KhaosUtils.isDevelopEnv()) {
//            String testFile = "/Users/tanmengxi/workspace/IDEA_/Khaos/khaos-plugin-core/src/test/resources/JobJson.json";
//            String fileContext = FileUtils.readFileAsString(testFile);
//            return fileContext;
//        }

        try {
            commandLine = parser.parse(options, args);
            userConfig = commandLine.getOptionValue("userConfig");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return userConfig;
    }

    public void addClassPath() {

    }

    public static void main(String[] args) {
        AppLaunch appLaunch = new AppLaunch();
        appLaunch.run(args);
    }

}
